package com.example;

import java.util.ArrayList;
import java.util.List;

import winterwell.jtwitter.Twitter;
import winterwell.jtwitter.TwitterException;
import winterwell.jtwitter.TwitterList;
import winterwell.jtwitter.Twitter.Status;
import winterwell.jtwitter.Twitter.User;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

/**
 * Responsible for pulling twitter updates from twitter.com and putting it into
 * the database.
 */
public class UpdaterService extends Service {
	static final String TAG = "UpdaterService";
	static final String ACTION_NEW_TWITTER_STATUS = "ACTION_NEW_TWITTER_STATUS";
	static final String ACTION_NEW_TWITTER_LIST = "ACTION_NEW_TWITTER_LIST";
	Twitter twitter;
	Handler handler;
	Updater updater;
	DbHelper dbHelper;
	SQLiteDatabase db;

	@Override
	public void onCreate() {
		super.onCreate();
		// Get shared preferences

		// Setup handler
		handler = new Handler();
		Log.d(TAG, "onCreate'd");
	}

	@Override
	public void onStart(Intent i, int startId) {
		super.onStart(i, startId);
		updater = new Updater();
		handler.post(updater);
		Log.d(TAG, "onStart'ed");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		handler.removeCallbacks(updater); // stop the updater
		db.close();
		Log.d(TAG, "onDestroy'd");
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	/** Updates the database from twitter.com data */
	class Updater implements Runnable {
		static final int STATUS_NOTIFICATION_ID = 47;
		static final int LIST_NOTIFICATION_ID = 48;
		static final long DELAY = 300000L;
		Notification notification;
		NotificationManager notificationManager;
		PendingIntent pendingIntent;

		Updater() {
			notificationManager = (NotificationManager) UpdaterService.this
					.getSystemService(Context.NOTIFICATION_SERVICE);
			notification = new Notification(
					android.R.drawable.stat_sys_download, "MyTwitter", System
							.currentTimeMillis());
			pendingIntent = PendingIntent.getActivity(UpdaterService.this, 0,
					new Intent(UpdaterService.this, Timeline.class), 0);
		}

		public void run() {
			boolean haveNewStatus = false;
			Log.d(UpdaterService.TAG, "Updater ran.");
			ArrayList<String> listTracker = new ArrayList<String>();

			try {
				twitter = new TwitterClient(getApplicationContext())
						.getTwitter();
				if (twitter == null) {
					Toast.makeText(getApplicationContext(),
							"User name or password is not set!",
							Toast.LENGTH_LONG).show();

				} else {
					List<Status> timeline = twitter.getFriendsTimeline();
					for (Status status : timeline) {
						ContentValues values = DbHelper
								.statusToContentValues(status);
						// Insert will throw exceptions for duplicate IDs
						Uri result = getContentResolver().insert(
								Timeline.TIMELINE_CONTENT_URI, values);
						if (result != null)
							haveNewStatus = true;
						Log.d(TAG, "Got status: " + status.toString());
					}

					List<TwitterList> lists = twitter.getLists();
					Log.d(TAG, "Lists Size: " + lists.size());

					List<User> listMembers;
					for (TwitterList list : lists) {
						
						String listName = list.getName();
						listTracker.add(listName);
						listMembers = list.getSubscribers();
						Log.d(TAG, "List Members Size: " + listMembers.size());

						// delete all the member so that if someone has been
						// deleted they no longer appear here
						getContentResolver().delete(
								Uri.parse(Timeline.LIST_CONTENT_URI.toString()
										+ "/" + listName), null, null);
						// add them all back
						for (User user : listMembers) {
							ContentValues row = new ContentValues();
							row.put("_id", listName);
							row.put("user", user.getScreenName());
							getContentResolver().insert(
									Timeline.LIST_CONTENT_URI, row);
						}

					}
					// delete all the lists that were deleted
					String where = "";
					if (listTracker.size() > 0) {
						StringBuffer sqlLists = new StringBuffer("'");
						for (String list : listTracker) {
							sqlLists.append(list);
							sqlLists.append("', '");
						}

						sqlLists.setLength(sqlLists.length() - 3);
						where = "_id not in (" + sqlLists.toString() + ")";

					}
					getContentResolver().delete(Timeline.LIST_CONTENT_URI,
							where, null);
				}
			} catch (TwitterException e) {
				Log.e(TAG, "Updater.run exception: " + e);
			}

			// If there's new status, send a broadcast & notify user
			if (haveNewStatus) {
				sendBroadcast(new Intent(ACTION_NEW_TWITTER_STATUS));
				Log.d(TAG, "run() sent ACTION_NEW_TWITTER_STATUS broadcast.");

				// Create the notification
				notification.setLatestEventInfo(UpdaterService.this,
						"New Twitter Status",
						"You have new tweets in the timeline", pendingIntent);
				notification.when = System.currentTimeMillis();

				notificationManager
						.notify(STATUS_NOTIFICATION_ID, notification);
			}
			sendBroadcast(new Intent(ACTION_NEW_TWITTER_LIST));
			Log.d(TAG, "run() sent ACTION_NEW_TWITTER_LIST broadcast.");
			pendingIntent = PendingIntent.getActivity(UpdaterService.this, 0,
					new Intent(UpdaterService.this, ListTimeline.class), 0);
			notification.setLatestEventInfo(UpdaterService.this,
					"New List Info", "Your lists have been updated",
					pendingIntent);
			notification.when = System.currentTimeMillis();
			notificationManager.notify(LIST_NOTIFICATION_ID, notification);

			// Set this to run again later
			handler.postDelayed(this, DELAY);

		}
	}
}
